package cn.com.inossem.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.db.DatabaseHelper;
import cn.com.inossem.model.DatePicjerInfo;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.ActivityStackControlUtil;
import cn.com.inossem.utils.Utils;

import com.foxykeep.datadroid.requestmanager.Request;

/**
 * 
 * 检索向导
 * 
 * <p>
 * detailed comment
 * 
 * @author szc 2015-8-24
 * @see
 * @since 1.0
 */
public class UpdateProjectActivity extends RequestActivity {

	RelativeLayout projectNameLayout, projectAddressLayout,
			projectNatureLayout, projectIndustryLayout, projectModelLayout,
			stationLayout, stationzhize;
	TextView projectNametext, projectAddresstext, projectNaturetext,
			projectIndustrytext, projectModeltext, stationtext, savedata,
			stationzhizetext;

	TextView time1, time2;
	EditText projectCommenttext;

	ImageView back;

	DatePicjerInfo mDateStar;
	DatePicjerInfo mDateEnd;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main_tab_layout);
		initView();

	}

	@Override
	public void onDestroy() {
		ActivityStackControlUtil.remove(this);
		super.onDestroy();
	}

	private void initView() {
		mDateStar = new DatePicjerInfo();
		mDateEnd = new DatePicjerInfo();
		// if (!ProjectXiangmuNameActivity.bean.getStartTime().equals("")) {
		// String[] timesText = ProjectXiangmuNameActivity.bean.getStartTime()
		// .split(".");
		// mDateStar.year = Integer.parseInt(timesText[0]);
		// mDateStar.month = Integer.parseInt(timesText[1]) - 1;
		// mDateStar.dayofmonth = Integer.parseInt(timesText[2]);
		// }
		// if (!ProjectXiangmuNameActivity.bean.getEndTime().equals("")) {
		// String[] timesText = ProjectXiangmuNameActivity.bean.getEndTime()
		// .split(".");
		// mDateEnd.year = Integer.parseInt(timesText[0]);
		// mDateEnd.month = Integer.parseInt(timesText[1]) - 1;
		// mDateEnd.dayofmonth = Integer.parseInt(timesText[2]);
		// }
		back = (ImageView) this.findViewById(R.id.back);
		back.setOnClickListener(this);
		savedata = (TextView) this.findViewById(R.id.savedata);
		savedata.setOnClickListener(this);

		time1 = (TextView) this.findViewById(R.id.time1);
		time1.setText(ProjectXiangmuNameActivity.bean.getStartTime());
		time1.setOnClickListener(this);
		time2 = (TextView) this.findViewById(R.id.time2);
		time2.setText(ProjectXiangmuNameActivity.bean.getEndTime());
		time2.setOnClickListener(this);

		projectNameLayout = (RelativeLayout) this
				.findViewById(R.id.projectName);
		projectNameLayout.setOnClickListener(this);
		projectAddressLayout = (RelativeLayout) this
				.findViewById(R.id.projectAddress);
		projectAddressLayout.setOnClickListener(this);
		projectNatureLayout = (RelativeLayout) this
				.findViewById(R.id.projectNature);
		projectNatureLayout.setOnClickListener(this);
		projectIndustryLayout = (RelativeLayout) this
				.findViewById(R.id.projectIndustry);
		projectIndustryLayout.setOnClickListener(this);
		projectModelLayout = (RelativeLayout) this
				.findViewById(R.id.projectModel);
		projectModelLayout.setOnClickListener(this);
		stationLayout = (RelativeLayout) this.findViewById(R.id.station);
		stationLayout.setOnClickListener(this);

		stationzhize = (RelativeLayout) this.findViewById(R.id.stationzhize);
		stationzhize.setOnClickListener(this);

		projectNametext = (TextView) this.findViewById(R.id.projectNametext);
		projectNametext.setText(ProjectXiangmuNameActivity.bean
				.getProjectName() + "");
		projectAddresstext = (TextView) this
				.findViewById(R.id.projectAddresstext);
		if (ProjectXiangmuNameActivity.bean.getProjectAddress() != 0) {
			projectAddresstext.setText(selectData_info("t_areas", "area_id="
					+ ProjectXiangmuNameActivity.bean.getProjectAddress()));
		} else {
			projectAddresstext.setText("");
		}
		projectNaturetext = (TextView) this
				.findViewById(R.id.projectNaturetext);
		if (ProjectXiangmuNameActivity.bean.getProjectNature() != 0) {
			projectNaturetext.setText(selectData_info1("t_dictionary", "id="
					+ ProjectXiangmuNameActivity.bean.getProjectNature()));
//			projectNaturetext.setText(ProjectXiangmuNameActivity.bean
//					.getProjectNature());
		} else {
			projectNaturetext.setText("");
		}

		projectIndustrytext = (TextView) this
				.findViewById(R.id.projectIndustrytext);
		if (ProjectXiangmuNameActivity.bean.getProjectIndustry() != 0) {
			projectIndustrytext.setText(selectData_info1("t_dictionary", "id="
					+ ProjectXiangmuNameActivity.bean.getProjectIndustry()));
		} else {
			projectIndustrytext.setText("");
		}

		projectModeltext = (TextView) this.findViewById(R.id.projectModeltext);
		if (!ProjectXiangmuNameActivity.bean.getProjectModel().equals("")) {
			String[] str = ProjectXiangmuNameActivity.bean.getProjectModel()
					.split(",");
			projectModeltext.setText(selectData_info1("t_dictionary", "id="
					+ str[0])
					+ (str.length > 1 ?  "等" + str.length + "个" :""));
		} else {
			projectModeltext.setText("");
		}

		stationtext = (TextView) this.findViewById(R.id.stationtext);
		if (!ProjectXiangmuNameActivity.bean.getStation().equals("")) {
			// stationtext.setText(selectData_info1("t_dictionary", "id="
			// + ProjectXiangmuNameActivity.bean.getStation()));
			// stationtext.setText(ProjectXiangmuNameActivity.bean.getStation());
			String[] str = ProjectXiangmuNameActivity.bean.getStation().split(
					",");
			stationtext
					.setText(selectData_info1("t_dictionary", "id=" + str[0])
							+ (str.length > 1 ? "等" + str.length + "个" : ""));
		} else {
			stationtext.setText("");
		}

		stationzhizetext = (TextView) this.findViewById(R.id.stationzhizetext);
		if (!ProjectXiangmuNameActivity.bean.getStationDuty().equals("")) {
			String[] str = ProjectXiangmuNameActivity.bean.getStationDuty()
					.split(",");
			stationzhizetext.setText(selectData_info1("t_dictionary", "id="
					+ str[0])
					+ (str.length > 1 ? "等" + str.length + "个" : ""));
		} else {
			stationzhizetext.setText("");
		}

		projectCommenttext = (EditText) this
				.findViewById(R.id.projectCommenttext);
		if (!ProjectXiangmuNameActivity.bean.getProjectComment().equals("")) {

			// String commenttext = new String(
			// Base64.decode(ProjectXiangmuNameActivity.bean
			// .getProjectComment()));

			projectCommenttext.setText(ProjectXiangmuNameActivity.bean
					.getProjectComment());
		}

	}

	private String selectData_info1(String tabname, String selection) {
		String name = "";
		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getReadableDatabase();
		Cursor cursor = db.query(tabname, null, selection, null, null, null,
				null);
		if (cursor.moveToFirst()) {
			name = cursor.getString(cursor.getColumnIndex("name_cn"));

		}
		cursor.close();
		db.close();
		dh.close();
		return name;
	}

	private String selectData_info(String tabname, String selection) {
		String name = "";
		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getReadableDatabase();
		Cursor cursor = db.query(tabname, null, selection, null, null, null,
				null);
		if (cursor.moveToFirst()) {
			name = cursor.getString(cursor.getColumnIndex("area_name"));

		}
		cursor.close();
		db.close();
		dh.close();
		return name;
	}

	@Override
	public Request getInitialRequest() {
		return null;

	}

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {
		if (bundle.containsKey(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS)) {
			if (bundle.getInt(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS) == 1) {
				Toast.makeText(this, "修改成功!", Toast.LENGTH_LONG).show();
				setResult(99);
				finish();
			} else {
				Toast.makeText(this, "修改失败!", Toast.LENGTH_LONG).show();
			}

		}
	}

	@Override
	public void onRequestError(int exceptionType) {

	}

	public int getContentViewId() {
		return R.layout.updateproject_layout;

	}
	
	private void setProTimeInfo(int year, int month, int day) {
		// 获得SharedPreferences对象
		SharedPreferences settings = this.getSharedPreferences("shared_pro_time" + Utils.messageInfo.userInfo.getId(), 0);
		int iyear = settings.getInt("year", 0);
		int imonth = settings.getInt("month", 0);
		int iday = settings.getInt("day", 0);
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date newDate = sdf.parse(year + "-" + month + "-" + day);
			Date oldDate = sdf.parse(iyear + "-" + imonth + "-" + iday);
			// 判断是否更早日期
			if (!newDate.before(oldDate)) {
				return;
			}
			/*if (year > iyear)
				return;
			int imonth = settings.getInt("month", 0);
			if (month > imonth)
				return;
			int iday = settings.getInt("day", 0);
			if (day > iday)
				return;*/
			// 获得可编辑对象
			SharedPreferences.Editor editor = settings.edit();
			editor.putInt("year", year);
			editor.putInt("month", month);
			editor.putInt("day", day);
			editor.commit();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	
	private int[] getProTimeInfo() {
		SharedPreferences settings = this.getSharedPreferences("shared_pro_time" + Utils.messageInfo.userInfo.getId(), 0);
		Calendar cal = Calendar.getInstance();
		return new int[]{settings.getInt("year", cal.get(Calendar.YEAR)), settings.getInt("month", cal.get(Calendar.MONTH)), cal.get(Calendar.DATE)};
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		int[] proTimes = getProTimeInfo();
		switch (v.getId()) {
		case R.id.time1:
			DatePickerDialog datePickerDialog = new DatePickerDialog(this,
					Datelistener, proTimes[0], proTimes[1],
					proTimes[2]);
			datePickerDialog.show();
			break;
		case R.id.time2:
			datePickerDialog = new DatePickerDialog(this, Datelistener1,
					proTimes[0], proTimes[1],
					proTimes[2]);
			datePickerDialog.show();
			break;
		case R.id.back:
			// finish();
			showDialog(COMMON_DIALOG);
			break;
		case R.id.savedata:
			if (ProjectXiangmuNameActivity.bean.getProjectName().equals("")) {
				Toast.makeText(this, "项目名称不能为空!", Toast.LENGTH_LONG).show();
				return;
			}
			// String str =
			// Base64.encode(projectCommenttext.getText().toString()
			// .getBytes());
			ProjectXiangmuNameActivity.bean
					.setProjectComment(projectCommenttext.getText().toString());
			String startTime = ProjectXiangmuNameActivity.bean.getStartTime();
			if ((startTime != null) && (!startTime.equals(""))) {
				String[] startTimes = startTime.split("\\.");
				setProTimeInfo(Integer.valueOf(startTimes[0]), Integer.valueOf(startTimes[1]) - 1, Integer.valueOf(startTimes[2]));
			}
				
			System.out.println(ProjectXiangmuNameActivity.bean.getStartTime()
					+ "-" + ProjectXiangmuNameActivity.bean.getEndTime());
			launchRequest(WooRequestFactory
					.addXiangmu(ProjectXiangmuNameActivity.bean));
			break;
		case R.id.projectName:// 名字
			intent = new Intent(this, NameActivity.class);
			intent.putExtra("type", 200);
			startActivityForResult(intent, 0);
			break;
		case R.id.projectAddress:// 地址
			intent = new Intent(this, CityActivity.class);
			intent.putExtra("type", 20);
			startActivityForResult(intent, 0);
			break;
		case R.id.projectNature:// 性质
			intent = new Intent(this, RetrieveItemActivity.class);
			intent.putExtra("type", 5);
			intent.putExtra("itemtype", 5);
			intent.putExtra("isflag", true);
			intent.putExtra("isdanxuan", true);
			intent.putExtra("idstr",
					ProjectXiangmuNameActivity.bean.getProjectNature() + "");
			startActivityForResult(intent, 0);
			break;
		case R.id.projectIndustry:// 行业
			intent = new Intent(this, RetrieveItemActivity.class);
			intent.putExtra("type", 2);
			intent.putExtra("itemtype", 2);
			intent.putExtra("isflag", true);
			intent.putExtra("isdanxuan", true);
			intent.putExtra("idstr",
					ProjectXiangmuNameActivity.bean.getProjectIndustry() + "");
			startActivityForResult(intent, 0);
			break;
		case R.id.projectModel:// 技能
			System.out
					.println("ProjectXiangmuNameActivity.bean.getProjectModel():"
							+ ProjectXiangmuNameActivity.bean.getProjectModel());
			intent = new Intent(this, RetrieveItemActivity.class);
			intent.putExtra("type", 3);
			intent.putExtra("idstr",
					ProjectXiangmuNameActivity.bean.getProjectModel());
			// intent.putExtra("itemtype", 3);
			intent.putExtra("isflag", true);
			// intent.putExtra("isdanxuan", true);
			startActivityForResult(intent, 0);
			break;
		case R.id.station:// 岗位
			intent = new Intent(this, RetrieveItemActivity.class);
			intent.putExtra("type", 4);
			intent.putExtra("isflag", true);
			intent.putExtra("idstr",
					ProjectXiangmuNameActivity.bean.getStation() + "");
			startActivityForResult(intent, 0);
			break;
		case R.id.stationzhize:// 岗位职责10962
			intent = new Intent(this, RetrieveItemActivity.class);
			intent.putExtra("type", 8);
			intent.putExtra("isflag", true);
			intent.putExtra("idstr",
					ProjectXiangmuNameActivity.bean.getStationDuty() + "");
			startActivityForResult(intent, 0);
			break;
		default:
			break;
		}
	}

	public void androidend(String value) {

		// byte[] key = Base64.decode(
		// "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4".getBytes(), Base64.DEFAULT);
		//
		// byte[] data = value.getBytes("UTF-8");
		//
		// System.out.println("ECB加密解密");
		// byte[] str3 = Des3.des3EncodeECB(key, data);
		// byte[] str4 = Des3.ees3DecodeECB(key, str3);
		//
		// System.out.println(new String(Base64.encode(str3, Base64.DEFAULT),
		// "UTF-8"));
		// System.out.println(new String(str4, "UTF-8"));

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case 2:
			int id = data.getIntExtra("id", 0);
			String name = data.getStringExtra("name");
			ProjectXiangmuNameActivity.bean.setProjectIndustry(id);
			projectIndustrytext.setText(name);
			break;
		case 3:
			String num = data.getStringExtra("num");
			name = data.getStringExtra("name");
			if (name.equals("全部"))
				name = "";
			String result = data.getStringExtra("result");
			ProjectXiangmuNameActivity.bean.setProjectModel(result);
			projectModeltext.setText(name + num);
			break;
		case 4:
			id = data.getIntExtra("id", 0);
			name = data.getStringExtra("name");
			result = data.getStringExtra("result");
			num = data.getStringExtra("num");
			ProjectXiangmuNameActivity.bean.setStation(result);
			if (name.equals("全部")) {
				name = "";
			}
			stationtext.setText(name + num);
			break;
		case 5:
			id = data.getIntExtra("id", 0);
			name = data.getStringExtra("name");
			ProjectXiangmuNameActivity.bean.setProjectNature(id);
			projectNaturetext.setText(name);
			break;
		case 8:
			id = data.getIntExtra("id", 0);
			name = data.getStringExtra("name");
			result = data.getStringExtra("result");
			num = data.getStringExtra("num");
			ProjectXiangmuNameActivity.bean.setStationDuty(result);
			stationzhizetext.setText(name + num);
			break;
		case 20:
			id = data.getIntExtra("id", 0);
			name = data.getStringExtra("name");
			ProjectXiangmuNameActivity.bean.setProjectAddress(id);
			System.out.print(name);
			projectAddresstext.setText(name);
			break;
		case 200:
			name = data.getStringExtra("name");
			ProjectXiangmuNameActivity.bean.setProjectName(name);
			projectNametext.setText(name);
			break;
		default:
			break;
		}
	}

	private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
		/**
		 * params：view：该事件关联的组件 params：myyear：当前选择的年 params：monthOfYear：当前选择的月
		 * params：dayOfMonth：当前选择的日
		 */
		@Override
		public void onDateSet(DatePicker view, int myyear, int monthOfYear,
				int dayOfMonth) {

			// 修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
			mDateStar.updateDate(myyear, monthOfYear, dayOfMonth);
			// 更新日期
			updateDate();

		}

		// 当DatePickerDialog关闭时，更新日期显示
		private void updateDate() {
			// 在TextView上显示日期
			String str = mDateStar.getYear() + "." + (mDateStar.getMonth() + 1)
					+ "." + mDateStar.getDayofmonth();
			try {
				if (ProjectXiangmuNameActivity.bean != null) {
					if (!ProjectXiangmuNameActivity.bean.getEndTime()
							.equals("")
							&& Utils.DateCompare(str,
									ProjectXiangmuNameActivity.bean
											.getEndTime())) {
						Toast.makeText(UpdateProjectActivity.this,
								"开始日期不能大于结束日期", Toast.LENGTH_LONG).show();
						return;
					}
				}
				time1.setText(str);
				ProjectXiangmuNameActivity.bean.setStartTime(str);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	private DatePickerDialog.OnDateSetListener Datelistener1 = new DatePickerDialog.OnDateSetListener() {
		/**
		 * params：view：该事件关联的组件 params：myyear：当前选择的年 params：monthOfYear：当前选择的月
		 * params：dayOfMonth：当前选择的日
		 */
		@Override
		public void onDateSet(DatePicker view, int myyear, int monthOfYear,
				int dayOfMonth) {

			// 修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
			mDateEnd.updateDate(myyear, monthOfYear, dayOfMonth);
			// 更新日期
			updateDate();

		}

		// 当DatePickerDialog关闭时，更新日期显示
		private void updateDate() {
			// 在TextView上显示日期
			String str = mDateEnd.getYear() + "." + (mDateEnd.getMonth() + 1)
					+ "." + mDateEnd.getDayofmonth();
			try {
				if (ProjectXiangmuNameActivity.bean != null) {
					if (!ProjectXiangmuNameActivity.bean.getStartTime().equals(
							"")
							&& Utils.DateCompare(
									ProjectXiangmuNameActivity.bean
											.getStartTime(), str)) {
						Toast.makeText(UpdateProjectActivity.this,
								"结束日期不能小于开始日期", Toast.LENGTH_LONG).show();
						return;
					}
				}
				time2.setText(str);
				ProjectXiangmuNameActivity.bean.setEndTime(str);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	final int COMMON_DIALOG = 1;
	boolean baicunflag = false;

	protected Dialog onCreateDialog(int id) { // 重写onCreateDialog方法
		Dialog dialog = null; // 声明一个Dialog对象用于返回
		switch (id) { // 对id进行判断
		case COMMON_DIALOG:
			Builder b = new AlertDialog.Builder(this);
			// b.setIcon(); //设置对话框的图标
			b.setTitle(R.string.baocuntishi); // 设置对话框的标题
			// b.setMessage(R.string.Ok); // 设置对话框的显示内容
			b.setPositiveButton( // 添加按钮
					R.string.Ok, new DialogInterface.OnClickListener() { // 为按钮添加监听器
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							baicunflag = true;
							if (ProjectXiangmuNameActivity.bean
									.getProjectName().equals("")) {
								Toast.makeText(UpdateProjectActivity.this,
										"项目名称不能为空!", Toast.LENGTH_LONG).show();
								return;
							}
							// String str =
							// Base64.encode(projectCommenttext.getText().toString()
							// .getBytes());
							ProjectXiangmuNameActivity.bean
									.setProjectComment(projectCommenttext
											.getText().toString());

							System.out.println(ProjectXiangmuNameActivity.bean
									.getStartTime()
									+ "-"
									+ ProjectXiangmuNameActivity.bean
											.getEndTime());
							launchRequest(WooRequestFactory
									.addXiangmu(ProjectXiangmuNameActivity.bean));
						}
					});
			b.setNegativeButton( // 添加按钮
					R.string.Cancel, new DialogInterface.OnClickListener() { // 为按钮添加监听器
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							finish();
						}
					});
			dialog = b.create(); // 生成Dialog对象
			break;
		default:
			break;
		}
		return dialog; // 返回生成Dialog的对象
	}
}
